#!/bin/bash
source comm.cfg

installmaster() {
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis -y
sed -i "s/bind 127.0.0.1/bind 0.0.0.0/g" /etc/redis/redis.conf
sed -i "561i maxmemory-policy allkeys-lru" /etc/redis/redis.conf
sed -i "792i requirepass $REDIS_PASSWORD" /etc/redis/redis.conf
sed -i "539i masterauth $REDIS_PASSWORD" /etc/redis/redis.conf
sed -i "s/port 6379/port $REDIS_PORT/" /etc/redis/redis.conf

systemctl restart redis-server
if [ $? -eq 0 ];then
    echo 'redis-server启动成功'
else
    echo 'redis-server启动失败'
fi
cat <<EOF > /etc/redis/sentinel.conf
port 5000
sentinel monitor mymaster ${MASTER} ${REDIS_PORT} 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel auth-pass mymaster ${REDIS_PASSWORD}
sentinel parallel-syncs mymaster 1
logfile "/var/log/sentinel.log"
daemonize yes
EOF

redis-server /etc/redis/sentinel.conf --sentinel
if [ $? -eq 0 ];then
    echo 'redis-sentinel启动成功'
else
    echo 'redis-sentinel启动失败'
fi
}

installslave() {
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis -y
sed -i "s/bind 127.0.0.1/bind 0.0.0.0/g" /etc/redis/redis.conf
sed -i "561i maxmemory-policy allkeys-lru" /etc/redis/redis.conf
sed -i "792i requirepass $REDIS_PASSWORD" /etc/redis/redis.conf
sed -i "539i masterauth $REDIS_PASSWORD" /etc/redis/redis.conf
sed -i "s/port 6379/port $REDIS_PORT/" /etc/redis/redis.conf
sed -i "532i replicaof $MASTER $REDIS_PORT" /etc/redis/redis.conf

systemctl restart redis-server
if [ $? -eq 0 ];then
    echo 'redis-server启动成功'
else
    echo 'redis-server启动失败'
fi
cat <<EOF > /etc/redis/sentinel.conf
port 5000
sentinel monitor mymaster ${MASTER} ${REDIS_PORT} 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel auth-pass mymaster ${REDIS_PASSWORD}
sentinel parallel-syncs mymaster 1
logfile "/var/log/sentinel.log"
daemonize yes
EOF
redis-server /etc/redis/sentinel.conf --sentinel
if [ $? -eq 0 ];then
    echo 'redis-sentinel启动成功'
else
    echo 'redis-sentinel启动失败'
fi
}

installredis() {
    if [ -z $REDIS_PORT ];then
        REDIS_PORT=6379
    fi
    ip a |grep ${MASTER}
    if [ $? -eq 0 ];then
        installmaster
    else
        installslave
    fi  
}

installredis
